<template>
  <div class="box">
     <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="add"/>
    <!-- 中间表格模块 -->
    <BaseTable
      :data="cargotableData"
      :columns="cargotableDataColumns"
      :tableHeight="tableHeight"
      :pagination="false"
      :loading="loading"
    ></BaseTable>

    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="startpage"
        :page-sizes="[10,  15, 20,25,30]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
      ></el-pagination>
    </div>
    <div class="leftbox">
      <el-drawer
              size="30%"

              :title="SJtype=='add'?'新增司机信息':'编辑司机信息'"
              :visible.sync="SJdrawer"
              direction="rtl"
      >
        <el-form status-icon  ref="Sj" size="small" :model="editData">
          <div class="form-t">
            <el-form-item label="司机" prop="driverName" style="position: relative" :label-width="formLabelWidth">
              <el-input
                      v-model="editData.driverName"
                      style="width:100%"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="driverTel" style="position: relative" :label-width="formLabelWidth">
              <el-input
                      v-model="editData.driverTel"
                      style="width:100%"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button size="small" type="primary" @click="SJaddUpdate()">确定</el-button>
        </div>
      </el-drawer>

      <el-drawer
              size="45%"
        :before-close="handleClose"
        :title="flag?'新增拖轮信息':'编辑拖轮信息'"
        :visible.sync="drawer"
        direction="rtl"
      >
        <el-form status-icon :rules="basisRules" ref="basisRulesRef" size="small" :model="form">
          <div class="form-t">
            <el-form-item label="拖轮名称" prop="nameCn" style="position: relative" :label-width="formLabelWidth">
              <el-input
                @input="form.nameCn=verifyfilter('char',form.nameCn)"
                v-model="form.nameCn"
                autocomplete="off"

                style="width:100%"
              ></el-input>
<!--              <div style="font-size: 12px;margin: 0;padding: 0;color: #F56C6C;position: absolute;bottom: -25px" v-if="responseNameb">存在相似船名</div>-->
            </el-form-item>
            <el-form-item label="马力" prop="speed" :label-width="formLabelWidth">
              <el-input
                @input="form.speed=verifyfilter('digit',form.speed)"
                v-model="form.speed"
                autocomplete="off"
                style="width:100%"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属作业公司" prop="compCode" :label-width="formLabelWidth">
              <el-select filterable v-model="form.compCode" placeholder="作业公司" style="width:100%">
                <el-option
                  v-for="(item, index) in selectCompany"
                  :key="index"
                  :label="item.companyName"
                  :value="item.companyCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" prop :label-width="formLabelWidth">
              <el-input
                @input="form.linkmanName=verifyfilter('char',form.linkmanName)"
                type
                v-model="form.linkmanName"
                autocomplete="off"
                style="width:100%"
              ></el-input>
            </el-form-item>

            <el-form-item label="拖轮排序" prop="sortNum" :label-width="formLabelWidth">
              <el-input type="number" min="1" v-model.number="form.sortNum" style="width:100%"></el-input>
            </el-form-item>

            <el-form-item label="是否外租：" :label-width="formLabelWidth">
              <el-radio-group v-model="form.isrent">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="UUID" prop :label-width="formLabelWidth">
              <el-input
                type
                v-model="form.uuid"
                autocomplete="off"
                style="width:100%"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
<!--        <div style="padding: 0 10px; box-sizing: border-box">-->
<!--          <div style="width: 100%;background: #F5F7FA;-->
<!--		border: 1px solid #e1e4eb;-->
<!--		line-height: 28px;-->
<!--		height: 37px;-->
<!--		padding-top: 8px;-->
<!--		border-bottom-width: 0;-->
<!--        border-radius: 4px 4px 0 0;">-->
<!--            <el-tooltip class="item" effect="dark" content='添加' placement="top" style="float: right;margin-bottom: 6px;margin-right: 14px">-->
<!--              <el-button size="mini" @click="addClick()" icon="el-icon-plus"></el-button>-->
<!--            </el-tooltip>-->
<!--          </div>-->

<!--          <div style="clear: both"></div>-->

<!--          <BaseTable-->
<!--                  class="sjClass"-->
<!--                  :data="driverData"-->
<!--                  :columns="driveColumns"-->
<!--                  :tableHeight="tableHeight-400"-->
<!--                  :pagination="false"-->
<!--                  :loading="SJLoading"-->
<!--          ></BaseTable>-->
<!--        </div>-->
        <div class="demo-drawer__footer">
          <el-button size="small" type="primary" @click="addUpdate()" :loading="tugLoading">{{ tugLoading ? '提交中 ...' : '保 存' }}</el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { rules } from '@/plugins/formRules'
import BaseTable from '@/components/BaseTable'
import { isObjectValueEqual } from '@/libs/date'
import headerSearch from './component/headerSearch'

export default {
  name: 'metadataTug',
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      driverData: [],
      SJLoading: false,
      driveColumns: [
        {
          prop: 'driverName',
          label: '司机'
        },
        {
          prop: 'driverTel',
          label: '联系方式'
        },
        {
          label: '操作',
          align: 'center',
          width: 230,
          render: (h, params) => {
            return h(
              'div',
              {
                class: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#0B6CD6;'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEditb(params.$index, params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    innerHTML:
                                  `<span style='color:#DA2821;'><i class='iconfont icon-shanchu' style="font-size: 12px"></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete(params.$index, params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],

      tugLoading: false,
      // 搜索框显示对象
      selectObject: [
        {
          name: '拖轮名称',
          type: 'inputVerify',
          verifyTpye: 'char',
          modelName: 'nameCn'
        },
        {
          name: '作业港区',
          type: 'select',
          modelName: 'compCode',
          selectData: this.selectCompany
        }
      ],
      cargotableDataColumns: [
        {
          prop: 'nameCn',
          label: '拖轮名称'
        },
        {
          prop: 'speed',
          label: '马力'
        },
        {
          prop: 'linkmanName',
          label: '联系人'
        },
        {
          prop: 'compName',
          label: '所属作业公司'
        },
        {
          prop: 'isrent',
          label: '是否外租',
          render(h, params) {
            if (params.row.isrent == '0') {
              return h('el-tag', {
                props: {
                  size: 'mini'
                },
                domProps: {
                  innerHTML: '否'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'warning'
              },
              domProps: {
                innerHTML: '是'
              }
            })
          }
        },
        {
          prop: 'sortNum',
          label: '拖轮排序',
          sortable: true
        },
        {
          label: '操作',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'div',
              {
                class: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('拖轮资料按钮修改') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEdit(params.$index, params.row)
                    }
                  }
                })

                // h('el-button', {
                //   props: {
                //     size: 'mini'
                //   },
                //   domProps: {
                //     innerHTML:
                //       "<i class='iconfont icon-tubiao_liebiaoshanchu' style='color:#DA2821'></i>删除"
                //   },
                //   on: {
                //     click: () => {
                //       click: this.handleDelete(params.row.id)
                //     }
                //   }
                // })
              ]
            )
          }
        }
      ],
      cargotableData: [],

      // 基础信息验证
      basisRules: {
        nameCn: [
          {
            required: true,
            message: '中文船名不能为空',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],

        speed: [
          {
            trigger: 'blur',
            message: '马力不能为空',
            required: true
          }
        ],
        compCode: [
          {
            required: true,
            message: '公司不能为空',
            trigger: 'blur'
          }
        ],
        linkmanName: [
          {
            required: true,
            message: '联系人不能为空',
            trigger: 'blur'
          }
        ],
        sortNum: [
          {
            trigger: 'blur',
            message: '排序不能为空',
            required: true
          }
        ]
      },
      compData: [],
      queryInfo: {
        nameCn: '',
        compCode: ''
      }, // 查询参数
      flag: false,
      responseNameb: '',
      SJdrawer: false,
      editData: {},
      form: {
        nameCn: '',
        delFlag: '',
        speed: '',
        linkmanName: '',
        compCode: '',
        isrent: '0',
        sortNum: ''
      },
      formLabelWidth: '120px', // form的item宽度
      drawer: false, // 新增修改
      relation: false, // 关联
      loading: false,
      tableData: [],
      nowData: {},

      // 分页
      startpage: 1,
      totalNum: 0,
      pagesize: 15,

      selectCompany: [], // 公司
      flagHint: false,
      menuFlag: false,
      menuArr: [],
      SJtype: ''
    }
  },
  async activated() {
    var menuArr = []
    var menuId = ''
    if (localStorage.getItem('menuArr')) {
      menuArr = JSON.parse(localStorage.getItem('menuArr'))
    }
    menuArr.map(item => {
      item.children.map(v => {
        if (window.location.href.includes(v.url)) {
          menuId = v.id
        }
      })
    })

    if (menuId) {
      this.menuArr = []
      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`, { timeout: 30000 })
        .then(res => {
          res.data.data.map(item => {
            this.menuArr.push(item.resourceName)
          })

          if (!this.menuArr.includes('拖轮资料按钮新增')) {
            this.menuFlag = false
          } else {
            this.menuFlag = true
          }
        }).catch((error) => {})
    }
    if (this.$store.state.app.searchResouce == 'menu') {
      this.queryInfo = {
        nameCn: '',
        compCode: ''
      }
      this.getListData()
      this.getCompanyList()
    }
  },
  watch: {
    form: {
      handler(newVal, oldVal) {
        this.flagHint = isObjectValueEqual(newVal, oldVal)
      },
      deep: true
    }
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight
    }
  },
  methods: {
    SJaddUpdate() {
      if (this.SJtype == 'add') {
        this.driverData.push(this.editData)
      } else {
        console.log(this.editData)
        this.driverData[this.editData.index] = this.editData
        this.driverData.push({})
        this.driverData.pop()
      }
      console.log(this.driverData, this.editData)
      this.SJtype = ''
      this.editData = {}
      this.SJdrawer = false
    },
    addClick() {
      this.SJtype = 'add'
      this.editData = {}
      this.SJdrawer = true
    },
    handleEditb(index, row) {
      console.log('index', index, row)
      this.SJtype = 'edit'
      this.editData = JSON.parse(JSON.stringify(row))
      this.editData.index = row.index
      this.SJdrawer = true
    },
    handleDelete(index, row) {
      console.log(index, row);

      this.driverData.splice(row.index, 1)
    },
    selectTrustOrder() {

    },
    async checkSame(val) {
      if (this.form.id) {
        var namecnId = this.form.id
      } else { var namecnId = '' }

      const resb = await this.$http.get(
        `/${this.$ServiceName}/api/external/mttugboat/${this.$version}/checktugboatname?nameCn=${val}&id=${namecnId}`
      )
      if (resb.data.data) {
        var arr = []
        resb.data.data.map(item => {
          arr.push(item.nameCn)
        })
        this.responseNameb = arr
      } else {
        this.responseNameb = ''
      }
    },
    // 获取select所属公司
    async getCompanyList() {
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/public/listsecondcomp`
      )
      this.selectCompany = res.data.data;
      var selectCompanyTemp = [];
      this.selectCompany.map(item => {
        var obj = {};
        obj.dictLabel = item.companyName;
        obj.dictValue = item.companyCode;
        selectCompanyTemp.push(obj)
      })
      this.selectObject[1].selectData = selectCompanyTemp;
    },

    handleClose(done) {
      if (this.flagHint) {
        this.$confirm('您已修改了数据，确定是否关闭？')
          .then(_ => {
            this.responseNameb = ''
            this.$refs['basisRulesRef'].clearValidate()
            done()
          })
          .catch(_ => {})
      } else {
        this.responseNameb = ''
        this.$refs['basisRulesRef'].clearValidate()
        done()
      }
    },

    // 搜索
    searchClick(searchData) {
      this.startpage = 1
      this.queryInfo = Object.assign(this.queryInfo, searchData);
      this.getListData()
    },
    // 查询数据table
    async getListData() {
      this.loading = true
      await this.$http.get(
        `/${this.$ServiceName}/api/external/mttugboat/queryall?pagesize=${this.pagesize}&startpage=${this.startpage}`,
        {
          params: this.queryInfo
        }
      ).then(res => {
        this.cargotableData = res.data.data.pages
        // 分页
        this.startpage = res.data.data.pageNum
        this.pagesize = res.data.data.pageSize
        this.totalNum = res.data.data.totalNum
        this.loading = false
      }).catch(error => { this.loading = false })
    },
    addUpdateNew() {
      // 传递的参数等待确认
      delete this.form.createBy
      delete this.form.createName
      delete this.form.createTime
      delete this.form.updateBy
      delete this.form.updateName
      delete this.form.updateTime
      delete this.form.delFlag
      delete this.form.buildDate

      this.selectCompany.forEach(v => {
        if (v.companyCode == this.form.compCode) {
          this.form.compName = v.companyName
        }
      })
      // flag为真进行添加操作
      this.$refs['basisRulesRef'].validate(async valid => {
        if (valid) {
          this.tugLoading = true
          if (this.flag) {
            delete this.form.id
            await this.$http.post(
              '/${this.$ServiceName}/api/external/mttugboat/add',
              this.form
            ).then(res => {
            //   this.driverData.map(item=>{
            //     item.tugboatId =  res.data.data
            //   })
              this.$message.success(res.data.msg)
              this.$nextTick(() => {
                this.$refs.basisRulesRef.resetFields()
              })
              // this.$http.post(
              //         '/${this.$ServiceName}/api/external/mtugboatdriver/v1/saveTugboatDriver',
              //         this.driverData
              // ).then(res =>{
              this.$message.success(res.data.msg)
              this.$nextTick(() => {
                this.$refs.basisRulesRef.resetFields()
              })
              this.drawer = false
              this.getListData()
              this.tugLoading = false
              this.form = {}
              // }).catch(error => {this.tugLoading = false})
              // this.drawer = false
              // this.getListData()
              // this.tugLoading = false
            }).catch(error => { this.tugLoading = false })
          } else {
            // 进行修改操作elseRules
            delete this.form.buildDate
            delete this.form.index
            await this.$http.put(
              '/${this.$ServiceName}/api/external/mttugboat/updatebyid',
              this.form
            ).then(res => {
              // this.driverData.map(item=>{
              //   item.tugboatId =  this.form.id
              // })
              // if(this.driverData.length==0){
              //   this.driverData = [{tugboatId:this.form.id}]
              // }
              // this.$http.post(
              //         '/${this.$ServiceName}/api/external/mtugboatdriver/v1/saveTugboatDriver',
              //         this.driverData
              // ).then(res =>{

              this.drawer = false
              this.$message.success(res.data.msg)
              this.responseNameb = ''
              this.getListData()
              this.tugLoading = false
              this.form = {}
              // }).catch(error => {this.tugLoading = false})
              // this.drawer = false
              // this.$message.success(res.data.msg)
              // this.responseNameb = ""
              // this.getListData()
              // this.tugLoading = false
            }).catch(error => { this.tugLoading = false })
          }
        } else {
          return false
        }
      })
    },
    async addUpdate() {
      if (this.form.nameCn) {
        if (this.form.id) {
          var namecnId = this.form.id
        } else { var namecnId = '' }

        const resb = await this.$http.get(
          `/${this.$ServiceName}/api/external/mttugboat/${this.$version}/checktugboatname?nameCn=${this.form.nameCn}&id=${namecnId}`
        )
        if (resb.data.data) {
          var flag = []
          var arr = []
          resb.data.data.map(item => {
            arr.push(item.nameCn)
          })
          flag = resb.data.data

          this.responseNameb = arr
        } else {
          this.responseNameb = ''
        }
        if (this.responseNameb) {
          if (flag[0].flag) {
            this.$message.error('存在重复拖轮名！')
            return
          }
          this.$confirm(`存在类似拖轮名称:${this.responseNameb},是否继续保存?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addUpdateNew()
          }).catch(() => {
          });
        } else {
          this.addUpdateNew()
        }
      } else {
        this.addUpdateNew()
      }
    },
    // 修改
    handleEdit(index, row) {
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form);
      this.drawer = true
      this.flag = false
      this.tugLoading = false
      this.form.buildDate = new Date(this.form.buildDate) // 时间date格式

      if (row.drivers) {
        this.driverData = JSON.parse(JSON.stringify(row.drivers))
      } else {
        this.driverData = []
      }
    },

    add() {
      this.flag = true
      this.drawer = true
      this.tugLoading = false
      this.form = {
        nameCn: '',
        delFlag: '',
        speed: '',
        linkmanName: '',
        compCode: '',
        isrent: '0',
        sortNum: ''
      }
      this.$nextTick(() => {
        this.$refs.basisRulesRef.resetFields()
      })
    },
    // 每页显示的条数
    handleSizeChange(val) {
      this.pagesize = val
      this.getListData()
    },
    // 当前页
    handleCurrentChange(val) {
      this.startpage = val
      this.getListData()
    }
    // async handleDelete(id) {
    //   const confirmRes = await this.$confirm(
    //     '此操作将永久删除该数据, 是否继续?',
    //     '提示',
    //     {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }
    //   ).catch(err => {})
    //   if (confirmRes !== 'confirm') {
    //     return this.$message.info('已经取消删除')
    //   }
    //   this.subDelete(id)
    // }
  }
}
</script>


<style lang="less" scoped>
.el-drawer__body {
  .el-form {
    padding: 20px;
    box-sizing: border-box;
  }
}

/deep/.vue-treeselect__control {
  height: 28px !important;
}

/deep/.vue-treeselect__control {
  background: none !important;
}

/deep/.vue-treeselect__placeholder,
/deep/.vue-treeselect__single-value {
  line-height: 28px !important;
  font-size: 12px !important;
}

// /deep/ .el-select > .el-input {
// 	width: 100% !important;
// }
// .leftbox /deep/ .el-input {
// 	width: 60% !important;
// }
// .leftbox /deep/ .el-select {
//   width: 100% !important;
// }
/deep/ .el-button--primary {
  background-color: #338ce8;
  border-color: #338ce8;
}

.page {
  background: #ffffff;
  border-radius: 4px 4px 0 0;
}

.headerspan {
  background: #ffffff;
  border-bottom: 1px solid #e1e4eb;
  line-height: 40px;
  padding-left: 1rem;
}

.headerspan-item {
  line-height: 40px;
  padding-left: 1rem;
  font-size: 14px;
  color: #606266;
  letter-spacing: 0;
}

.form-t /deep/ .el-form-item__content {
  margin-left: 1rem !important;
  display: flex;
}

.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}

.title {
  background: #f5f7fa;
  height: 40px;
  line-height: 40px;

  p {
    font-family: MicrosoftYaHei;
    font-size: 16px;
    color: #303133;
    letter-spacing: 0;
    line-height: 16px;
    padding-left: 14px;
    line-height: 40px;
  }
}

/deep/ .el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

/deep/ .demo-drawer__footer {
  text-align: right;
  padding-right: 1rem;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

/deep/ .el-table .cell {
  white-space: nowrap;
}

/deep/ .el-form-item--mini .el-form-item__label {
  line-height: 0;
}

/deep/ .el-pagination {
  text-align: right;
  padding: 10px 20px;

  .el-input {
    width: none;
  }
}

/deep/ .el-table th > .cell {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  color: #606266;
}

/deep/ .el-table .el-button:focus,
.el-table .el-button:hover {
  background-color: #fff;
  border: 1px solid #e1e4eb;
}

/deep/ .el-table .el-button--mini {
  color: #1684f6;
  border-color: transparent;
  background: transparent;
}

/deep/ .el-table th {
  border-left: 1px solid #ebeef5;
}

/deep/ .el-table th:nth-child(1) {
  border-left: none;
}

/deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f5f7fa;
}

.btn /deep/ .el-button--mini,
.el-button--mini.is-round {
  padding: 7px;
}

/deep/.el-pagination.is-background .btn-next,
/deep/ .el-pagination.is-background .btn-prev,
/deep/ .el-pagination.is-background .el-pager li {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 3px;
  border-radius: 3px;
}

/deep/ .el-drawer__open .el-drawer.rtl {
  background: #f5f7fa;
}

/deep/ .el-button + .el-button {
  margin-left: 3px;
}

.selectBox {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  display: flex;
  align-items: center;
  padding-left: 16px;
}

.kehuguanxi /deep/ .el-drawer__open .el-drawer.rtl {
  width: 30% !important;
}

/deep/ .el-drawer__body {
  overflow-y: auto;
  padding-bottom: 50px;
}

.formt-itm {
  border-bottom: 1px solid gainsboro;
  margin-bottom: 4px;
  padding-left: 1rem;
  padding-right: 1rem;
  display: flex;
  justify-content: space-between;
  letter-spacing: 0;
  font-family: MicrosoftYaHei;
  font-size: 14px;
  color: #303133;
  line-height: 40px;

  i {
    color: #909399;
  }
}
.sjClass{
  .el-table{
    min-height: 300px!important;
    margin-bottom: 30px;
  }
}
</style>
<style>
  .el-message-box__message{
    word-wrap:break-word!important;
    max-height: 100px;
    overflow: auto;
  }

</style>
